<template>
  <q-page class="q-pa-md">
    <div class="row items-center q-gutter-x-md">
      <user-profile :key="userProfileKey" />
    </div>
    <!-- 分割线 -->
    <hr class="my-divider">

    <div class="search-container">
      <!-- 搜索框 -->
      <q-input
        v-model="searchKeyword"
        outlined
        rounded
        placeholder="请输入搜索内容(对方名字或者Id)..."
        class="search-input"
        @update:model-value="handleSearch"
      >
        <template #prepend>
          <q-icon name="search" />
        </template>
      </q-input>

      <!-- 搜索结果列表 -->
      <q-list
        v-if="searchResults.length > 0"
        class="search-results bg-white rounded-borders shadow-4"
      >
        <!-- 动画效果 -->
        <transition-group
          name="fade"
          tag="div"
        >
          <q-item
            v-for="result in limitedResults"
            :key="result.id"
            v-close-popup
            clickable
            class="q-my-sm"
            @click="handleResultClick(result)"
          >
            <!-- 左侧图标或头像 -->
            <q-item-section avatar>
              <q-avatar>
                <img :src="result.avatar_url">
              </q-avatar>
            </q-item-section>

            <!-- 主内容区域 -->
            <q-item-section>
              <!-- 高亮关键字 -->
              <q-item-label>
                <span class="text-primary">{{ result.username }}</span>
              </q-item-label>
            </q-item-section>
            <q-item-section>
              <!-- 高亮关键字 -->
              <q-item-label caption>
                <span class="text-primary">{{ result.nickname }}</span>
              </q-item-label>
            </q-item-section>

            <!-- 右侧操作按钮（可选） -->
            <q-item-section side>
              <q-icon
                name="chevron_right"
                color="grey"
                size="20px"
              />
            </q-item-section>
          </q-item>
        </transition-group>
      </q-list>
    </div>
    <!-- 分割线 -->
    <hr class="my-divider">
    <image-view :key="imageViewKey" />
  </q-page>
</template>

<script>
import {
  defineComponent, ref, computed, defineAsyncComponent,
} from 'vue';
import { useQuasar } from 'quasar';
import { useAuthStore } from 'src/stores/auth.js';
import { debounce } from 'lodash-es';
import member from 'src/api/member.js';

export default defineComponent({
  name: 'Home',
  components: {
    UserProfile: defineAsyncComponent(() => import('components/UserProfile.vue')),
    ImageView: defineAsyncComponent(() => import('components/ImageView.vue')),
  },
  setup() {
    const $q = useQuasar();
    const auth = useAuthStore();

    // 搜索相关逻辑
    const searchKeyword = ref('');
    const userProfileKey = ref(0);
    const imageViewKey = ref(0);
    const searchResults = ref([]);
    const limitedResults = computed(() => searchResults.value.slice(0, 5));

    const handleSearch = debounce(async (keyword) => {
      if (!keyword) {
        searchResults.value = [];
        return;
      }

      try {
        const response = await member.searchApi(keyword);
        searchResults.value = response.data.data;
      } catch (error) {
        $q.notify({
          type: 'negative',
          message: '搜索失败，请稍后重试',
        });
      }
    }, 500);

    const handleResultClick = (result) => {
      // console.log('选中结果:', result);
      auth.saveFriend(result);

      userProfileKey.value += 1; // 更新 key 值，触发重新渲染
      imageViewKey.value += 1; // 更新 key 值，触发重新渲染

      searchKeyword.value = '';
      searchResults.value = [];
    };

    return {
      searchKeyword,
      searchResults,
      limitedResults,
      handleSearch,
      handleResultClick,

      userProfileKey, // 初始 key 值
      imageViewKey,
    };
  },
});
</script>

<style scoped>
.upload-area {
  border: 2px dashed #ccc;
  border-radius: 8px;
  cursor: pointer;
  min-height: 200px;
  overflow: hidden;
}

.upload-area:hover {
  border-color: var(--q-primary);
}

.overlay {
  background: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: opacity 0.3s;
}

.upload-area:hover .overlay {
  opacity: 1;
}

.empty-area {
  height: 200px;
  color: #666;
}

.row {
  margin-bottom: 20px;
}

.q-avatar img {
  object-fit: cover;
}

.text-h6 {
  font-weight: bold;
  color: #333;
}

.my-divider {
  border: none;
  height: 1px;
  background-color: #ccc;
  /* 分割线颜色 */
  margin: 20px 0;
  /* 上下外边距 */
}

.search-input {
  width: 100%;
}

.search-results {
  max-height: 400px;
  overflow-y: auto;
  margin-top: 8px;
  border: 1px solid rgba(0, 0, 0, 0.12);
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}
</style>
